#include "stdafx.h"

#include <QWebSocket>

#include "ClientManager.h"
#include "Session.h"
#include "TServer.h"
#include <QJsonObject>


//Session::Session(QWebSocket *client, int channel)
//    :_client(client), _channel(channel)
//{
//}

Session::Session()
    : _client(ClientManager::instance()->popFirstActiveClient()->websocket), _channel(newChannel())
{

}

Session::~Session()
{
}

void Session::close() const
{
    this->send("close");
}

void Session::activate() const
{
    this->send("activate");
}

void Session::send(const QString &type, const QVariantMap &arg) const
{
    auto msg = QJsonDocument(
        QJsonObject{
            { "type", type },
            { "arg", QJsonObject::fromVariantMap(arg) },
            { "channel", _channel }
    }).toJson(QJsonDocument::Indented);
    _send(msg);
}

void Session::send(const QString &type) const
{
    auto msg = QJsonDocument(
        QJsonObject{
            { "type", type },
            { "channel", _channel }
    }).toJson(QJsonDocument::Indented);
    _send(msg);
}

void Session::_send(const QString &text) const
{
    TServer::instance()->sendHelper(_client, text);
}

int Session::_lastUnusedChannel = 0;
